What are the different types of variables present in PHP?
There are 8 primary data types in PHP which are used to construct the variables. They are:

  • Integers: Integers are whole numbers without a floating-point. Ex: 1253.
  • Doubles: Doubles are floating-point numbers. Ex: 7.876
  • Booleans: It represents two logical states- true or false.
  • NULL: NULL is a special type that only has one value, NULL. When no value is assigned to a variable, it can be assigned with NULL.
  • Arrays: Array is a named and ordered collection of similar type of data. Ex: $colors = array("red", "yellow", "blue");
  • Strings: Strings are a sequence of characters. Ex: “Hello InterviewBit!”
  • Resources: Resources are special variables that consist of references to resources external to PHP(such as database connections).
  • Objects: An instance of classes containing data and functions. Ex: $mango = new Fruit();

What is the difference between the GET and POST methods?
Following are the key differences between <GET> and <POST>.

GET Method.
 - It submits all the Name-Value pairs as a query string in the URL.
 - This method is not secure and reveals the data transmitted with the URL.
 - The allowed length of the GET string should not exceed 2048 characters.
 - If the Form tag does not contain any method name, GET will take over as default.
 - The payload data is in text format. It accepts only ASCII values.
 - GET is beneficial for performing data retrieval operations.

POST Method.
 - It submits all the Name-Value pairs in the Message Body of the request.
 - Unlike the GET, the Post method is secure as the Name-Value pairs do not appear in the location bar of the web browser.
 - Since the payload gets encoded into the request, it doesn’t show up as part of the URL.
 - There is no restriction on the length of the string (i.e. the amount of data transmitted).
 - In case, the POST method is in use and page refresh happens at the same time, then a prompt will occur before processing the request.
 - If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
 - It has no restriction on data usage and permits binary data also.
 - POST is beneficial for performing both insert and update operations.

What are Magic functions in PHP?
They are special PHP functions that start with a double underscore <__>. None of these are stand-alone. And it is mandatory to define them inside a Class.

Below are some facts about the Magic functions in PHP.

 - It is the programmer who defines the PHP magic function. Once the programmer provides the definition, PHP enables him to achieve powerful things using the Magic function.
 - PHP does not allow us to call it directly from the code. Instead, the call happens indirectly.
Let’s see an example.
class Animal {
   // height of animal 
   public $height;
   // weight of animal
   public $weight;
   // code
   public function __construct($height, $weight)
   {
      $this->height = $height;  //set the height instance variable
      $this->weight = $weight; //set the weight instance variable
   }
}
Now, if we instantiate the Animal Class using the following line of code.
Animal obj = new Animal(6, 150);
It will automatically call the <__construct()> function and create an object obj, of the Animal class, with its height as 6 and weight as 150.

Here is a list of some powerful magic functions supported by PHP.

__construct() ,  __destruct()  ,    __call()   ,  __callStatic()  ,  __get(),  __set()     , __isset(), __unset(),  __sleep(),  __wakeup(),   __toString()  , __invoke(), __set_state() ,  __clone().

What is a .htacces file in PHP?
The <.htaccess> is a configuration file used on the servers to run the Apache Web Server software. If this file is present in the directory, then the Apache Web Server will load it into memory and execute it.
It acts as a powerful tool to alter the configuration of the Web Server software by enabling/disabling the additional functionality and features that it offers.
These include :
 - The redirection feature is like an occurrence of 404, file not found.
 - More advanced functions such as content password protection or image hotlink prevention.

What is the maximum file size that PHP allows to upload? How can we increase it?
The standard limit in PHP to upload a file is 2MB. However, we can change this value by making modifications in the php.ini file. We have to alter the value of upload_max_filesize and restart all the services.

What is a final class in PHP?
The final class is a unique object-oriented concept that prohibits a class from being inherited. We can use it to protect the methods of the base class from getting overridden by the child classes.

What are the differences between echo() and print() methods?
Following are the key differences between echo() and print() statements.

Echo:
 - It can accept multiple expressions.
 - Since it does not return any value, so responds a bit faster.
 - The echo statement displays the output on the user screen. Its syntax supports using echo with or without parentheses.
 - Multiple arguments are allowed if separated with <,>.
 - It doesn’t return any value.

Print:
 - It cannot accept multiple expressions.
 - Returning a value makes it a little slower than the echo.
 - The print statement displays the output on the user screen. Its syntax supports using print with or without parentheses.
 - Multiple arguments are not allowed.
 - Interestingly, it will always return the value 1.

What are visibility keywords in PHP?
We can set the visibility of a Property or Method by prefixing the declaration with the following keywords public, protected, or private.

  • A public specifier signifies that the members are accessible from everywhere within your application.
  • A protected specifier indicates that the members are accessible from within the class, the one that inherits it, and from the parent as well.
  • Private specifier restricts that the members should only be accessible from within the class.

What is Type Juggle in PHP?
In PHP, mentioning the type of the variable is not required for declaring a variable. The data type is determined implicitly, by the value/context of the variable. If we assign an integer value to a variable $num, then it becomes of type integer, implicitly. If we assign a string value to the variable $str, it becomes of type string.

Let’s take an example.

$num3 = $num1 + $num2

Here, if $num1 is an integer, PHP also treats $num2 and $num3 as integers.

What is the use of the header() function in PHP?
The header() function sends a raw HTTP header to the client browser. Its rule is to call this function always, before sending the actual output. For example, we don’t print any HTML element, before using the header() function.

What is a Session in PHP? How does PHP manage the lifecycle of a session?
Sessions are data structures that provide a way to store user-specific data and associate it with a unique session ID. However, PHP sessions also solve the following problems.

A session creates a file in a temporary directory on the server to cache the registered session variables and their values. This data will be accessible to all pages on the site during that stay.

PHP uses a php.ini file to get hold of the server settings. This file also specifies the location of the session file under the <session.save_path>. The developers can make sure that this setting points to a correct value before using the session variable.

While building up a session following events happen.
1. PHP generates PHPSESSID such as “c69dc153f003406b9a0242ad4c505baa”.
2. The PHP engine creates a file for every new session at the designated location. It bears the name of the unique identifier prefixed by <sess_>.
e.g. sess_c69dc153f003406b9a0242ad4c505baa.
3. When PHP gets a request from the browser or a client to access the session variable, it retrieves the session string from the PHPSESSID cookie.
4. A session comes to an end if the user decides to close the browser. However, the server could also terminate it after a certain inactivity period.

How do Sessions differ from Cookies in PHP?
Sessions keep data on the server (safe, holds more). They use a small cookie for ID. Cookies keep data on the user’s side (small size, less safe). Use sessions for logins, cookies for choices like themes.

How will you enable error reporting in PHP?
In PHP, we use the <error_reporting> function, to turn on error reporting for a particular file. The other way is to enable error reporting for all the files on the web server by editing the php.ini file.

Let’s get more clarity on how to enable error reporting in PHP.

<?php
//Disable all error reports
error_reporting(0);
//Enable basic runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
//Allow E_NOTICE to catch uninitialized variables or variable name
//or misspellings
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
//Allow all PHP errors
error_reporting(-1);
//Allow all PHP errors
 error_reporting(E_ALL);
//Alternate way to allow all errors in PHP
ini_set('error_reporting', E_ALL);
?>

Display Errors in PHP.
The <display_error> setting determines whether errors get printed on the screen or hidden from the user.
It gets used in conjunction with the error_reporting function as shown in the example below.

ini_set('display_errors',1);
error_reporting(E_ALL);
Modify the php.ini file.
If we want to see error reports for all our files, then just go to the web server and add the following option in the php.ini file for the website.
error_reporting=E_ALL
Explain Error Handling in PHP: Differences between errors, warnings, and exceptions.
Errors stop code (like bad setup or run fails). Warnings are small issues (like missing data). Exceptions are objects you throw for custom fixes. Use try-catch to handle them well.

What are Superglobals in PHP?
Superglobals are specially-defined array variables in PHP that make it easy for the user to get information about a request or its context. This data can come either from different URLs, HTML forms, cookies, sessions, and the Web server itself.
_GET represents the data forwarded to the PHP script in a URL. It applies to URLs that are directly accessible and also to form submissions that use the GET method.
_POST It represents the data forwarded to the PHP script via HTTP POST. It is a form that includes a method POST.
_COOKIE represents the data available to a PHP script via HTTP cookies.
_REQUEST It is a combination of $_GET, $_POST, and $_COOKIE.
_SESSION It represents the data available to a PHP script that was earlier, stored in a session._SERVER Superglobal represents the data available to a PHP script, from the Web server itself.
_ENV represents the data available to a PHP script from the environment in which PHP is running.
_FILES represents the data available to a PHP script from HTTP POST file uploads. Using $_FILES is currently the most preferred way to handle uploaded files in PHP.

What’s the difference between unlink() and unset() in PHP?
unlink() removes files from your computer’s storage. It helps clean up after uploads. unset() clears data from a variable or list spot. It frees space in memory but does not touch files.

Explain PHP Traits and when to use them.
Traits let you share code in PHP, which only allows one parent class. They act like small classes for methods and data. Use them to add the same features to different classes without repeats, like adding logs to many parts.

What are Abstract Classes and Interfaces? When to use each?
Abstract classes give some ready code (shared parts); interfaces set rules (no code, just what to do). Use abstracts for “is a type of” (like Base Page); interfaces for “can do this” (like Can Log).

Explain Composer and Autoloading in PHP.
Composer adds and handles add-on tools/packages. Autoloading (PSR-4) brings in classes when needed via a setup file.

What’s the role of Dependency Injection in PHP?
Dependency Injection gives needed parts from outside (like in setup or setter). It makes code loose and easy to test.

<?php  
interface Logger { public function log($msg); }  
class FileLogger implements Logger { public function log($msg) { file_put_contents('log.txt', $msg); } }  

class Service {  
    private $logger;  
    public function __construct(Logger $logger) { $this->logger = $logger; }  
    public function work() { $this->logger->log("Working"); }  
}  

$service = new Service(new FileLogger());  
$service->work();  
?>